package com.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import com.wechat.domain.condition.WechatUserCondition;
import com.wechat.domain.po.ArticleItem;
import com.wechat.domain.po.InMsgPo;
import com.wechat.domain.po.OutMsgPo;
import com.wechat.domain.po.WechatUserPo;
import com.wechat.service.WechatUserService;
import com.wechat.util.BeanXmlUtil;
import com.wechat.util.HttpClient4Util;
import com.wechat.util.SHA1Util;
import com.wechat.util.WechatUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.StringWriter;
import java.util.*;

@Slf4j
@Controller
public class IndexController {

    @Autowired
    private WechatUserService wechatUserService;

    @Value("${token}")
    private String token;

   /*
   *  验证消息的确来自微信服务器
   * */
    @RequestMapping(value = "/wechat",method = {RequestMethod.GET})
    @ResponseBody
    public void wechatValidate(HttpServletRequest request,HttpServletResponse response){
        log.info("==========wechat==============");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce =  request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        try {
            ArrayList<String> list=new ArrayList<String>();
            list.add(nonce);
            list.add(timestamp);
            list.add(token);
            Collections.sort(list);
            String enCodeStr = SHA1Util.encode(list.get(0)+list.get(1)+list.get(2));
            if(signature.equals(enCodeStr)){
                response.getWriter().print(echostr);
                response.getWriter().flush();
            }
        }catch (Exception e){
            log.info(e.getMessage());
        }
    }

    /*
     * 消息处理
     * */
    @RequestMapping(value = "/wechat",method = {RequestMethod.POST})
    @ResponseBody
    public Object handleMessage(@RequestBody InMsgPo inMsgPo) throws Exception{
        log.info("=======================handleMessage============================");
        OutMsgPo outMsgPo = new OutMsgPo();
        //发送方
        outMsgPo.setFromUserName(inMsgPo.getToUserName());
        //接收方
        outMsgPo.setToUserName(inMsgPo.getFromUserName());
        //消息创建时间
        outMsgPo.setCreateTime(new Date().getTime());
        //消息类型
        String msgType = inMsgPo.getMsgType();

        if(msgType.equals("text")){
            //消息内容
            outMsgPo.setContent(inMsgPo.getContent());
            outMsgPo.setMsgType("text");
        }else if(msgType.equals("image")){
            //消息内容
            outMsgPo.setMediaId(new String[]{inMsgPo.getMediaId()});
            outMsgPo.setMsgType("image");
        }else if(msgType.equals("event")){
            if(inMsgPo.getEvent().equals("subscribe") || inMsgPo.getEvent().equals("SCAN")){
//                outMsgPo.setMsgType("text");
//                outMsgPo.setContent("欢迎关注!");
                //回复图文详细
                outMsgPo.setMsgType("news");
                outMsgPo.setArticleCount(1);
                //设置图文明细列表
                ArticleItem item = new ArticleItem();
                item.setTitle("点击授权登录");
                item.setPicUrl("http://106.15.91.141/images/80000167f7a182304d5d2f94c05444e4.blob");
                item.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxef2bc7deed36d1b7&redirect_uri=http://daxuexiu.cn/wechat/index&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
                outMsgPo.setItem(new ArticleItem[] {item});
            }else if(inMsgPo.getEvent().equals("unsubscribe")){

            }else if(inMsgPo.getEvent().equals("CLICK")){
                if(inMsgPo.getEventKey().equals("V1001_LOGIN")){
                    outMsgPo.setMsgType("news");
                    outMsgPo.setArticleCount(1);
                    //设置图文明细列表
                    ArticleItem item = new ArticleItem();
                    item.setTitle("点击授权登录");
                    item.setPicUrl("http://106.15.91.141/images/80000167f7a182304d5d2f94c05444e4.blob");
                    item.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxef2bc7deed36d1b7&redirect_uri=http://daxuexiu.cn/wechat/index&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
                    outMsgPo.setItem(new ArticleItem[] {item});
//                    ArticleItem item = new ArticleItem();
//                    item.setTitle("【宜邻购】南京泽坤智能科技有限公司");
//                    item.setPicUrl("https://elingou.oss-cn-hangzhou.aliyuncs.com/img/wx/logo.png");
//                    item.setUrl("http://wx.elingou.com/ylg/index.html?from=singlemessage");
//                    item.setDescription("http://wx.elingou.com/ylg/index.html?from=singlemessage");
//                    outMsgPo.setItem(new ArticleItem[] {item});
                }else if(inMsgPo.getEventKey().equals("V1001_MOBILE")){
                    //消息内容
                    outMsgPo.setContent("联系人:岳云龙\n电话:17626019334\n地址:江苏南京市雨花台区软件大道\n\n");
                    outMsgPo.setMsgType("text");
                }else if(inMsgPo.getEventKey().equals("V1001_GOOD")){
                    outMsgPo.setContent("点赞成功!");
                    outMsgPo.setMsgType("text");
                }
            }
        }
        //bean转化为xml
        StringWriter sw = BeanXmlUtil.beanToXml(outMsgPo);
        System.out.println(sw.getBuffer().toString());
        return sw.getBuffer().toString();
    }

    /*redirect_uri回调得到code*/
    @RequestMapping(value = "/index",method = {RequestMethod.GET})
    public String index(String code, String state, Model model) throws Exception{
        log.info("=================index========================");
        model.addAttribute("code",code);
        return "index";
    }

    /*得到二维码*/
    @RequestMapping(value = "/ticket",method = {RequestMethod.GET})
    @ResponseBody
    public String ticket() throws Exception{

        /*获取网页接口access_token*/
        String access_token = WechatUtil.getAccessToken();

        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + access_token;

       // {"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": 123}}}
       // {\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": 123}}}
        String strResult = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"test\"}}}";

        String ret = HttpClient4Util.doPost(url,strResult);
        JSONObject json = JSONObject.parseObject(ret);
        String ticket = (String) json.get("ticket");

        String qrcodeImgUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;

        return  qrcodeImgUrl;
    }

    public static String getContent(String content, Map<String, Object> paramMap) throws Exception {
        String newMessage = content;
        if (paramMap != null && paramMap.size() != 0) {
            for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                newMessage = newMessage.replace("${" + entry.getKey() + "}", entry.getValue() != null ? entry.getValue().toString() : "");
            }
        }
        return newMessage;
    }

    public static void main(String[] args) throws Exception{

        String access_token = WechatUtil.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        url = url.replace("ACCESS_TOKEN", access_token);
        String content = "{\n" +
                "\n" +
                "\t\"touser\": \"${openId}\",\n" +
                "\t\"template_id\": \"${templateId}\",\n" +
                "\t\"url\": \"http://weixin.qq.com/download\",\n" +
                "\t\"data\": {\n" +
                "\t\t\"result\": {\n" +
                "\t\t\t\"value\": \"${result}\",\n" +
                "\t\t\t\"color\": \"#173177\"\n" +
                "\t\t},\n" +
                "\t\t\"withdrawMoney\": {\n" +
                "\t\t\t\"value\": \"${withdrawMoney}\",\n" +
                "\t\t\t\"color\": \"#173177\"\n" +
                "\t\t},\n" +
                "\t\t\"withdrawTime\": {\n" +
                "\t\t\t\"value\": \"${withdrawTime}\",\n" +
                "\t\t\t\"color\": \"#173177\"\n" +
                "\t\t},\n" +
                "\t\t\"endTime\": {\n" +
                "\t\t\t\"value\": \"${endTime}\",\n" +
                "\t\t\t\"color\": \"#173177\"\n" +
                "\t\t},\n" +
                "\t\t\"remark\": {\n" +
                "\t\t\t\"value\": \"${remark}\",\n" +
                "\t\t\t\"color\": \"#173177\"\n" +
                "\t\t}\n" +
                "\t}\n" +
                "}\n";

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("openId","ol8DI6VIFt7sagaFFu7H1dNVstls");
        map.put("templateId","2QBdsSG3Wpdxl4DtPkTbBZwSbwJwB9NOsRi0YT8FYAs");
        map.put("result","恭喜赵先生获得碧桂园代码大赛一等奖！");
        map.put("withdrawMoney","1000000元");
        map.put("withdrawTime","2021年6月1日");
        map.put("endTime","2021年6月10日");
        map.put("remark","");

        String contentWechatSub = getContent(content, map);
        System.out.println(contentWechatSub);
        try {
            String ret = HttpClient4Util.doPost(url,contentWechatSub);
            System.out.println(ret);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 获取unionId
        String reqUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        reqUrl = reqUrl.replace("ACCESS_TOKEN",access_token)
                .replace("OPENID","ol8DI6VIFt7sagaFFu7H1dNVstls");

        try {
            String ret = HttpClient4Util.Get(reqUrl);
            System.out.println(ret);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /*授权登录*/
//    @RequestMapping(value = "/login", method = RequestMethod.POST)
//    @ResponseBody
//    public Map<String,Object> login(HttpServletRequest request, HttpServletResponse response,String code) throws Exception {
//        Map<String,Object> map = new HashMap<String, Object>();
//        if (StringUtils.isBlank(code)){
//            map.put("result","fail");
//            map.put("code",202);
//            return map;
//        }
//        /*先刷新webOAuthAccessToken*/
////        Integer result = WechatUtil.getWebOAuthRefreshToken(code,WechatUtil.getRefreshToken());
////        if(1 == result){
//            /*1表示webOAuthAccessToken已过期需要重新获取webOAuthAccessToken*/
//            WechatUtil.getWebOAuthAccessToken(code);
////        }
//        /*获取用户信息*/
//        String uesrInfo = WechatUtil.getUserInfo();
//        JSONObject myJson = JSONObject.parseObject(uesrInfo);
//        System.out.println("JSON-----"+myJson.toString());
//        System.out.println("名字-----"+myJson.getString("nickname"));
//        System.out.println("头像-----"+myJson.getString("headimgurl"));
//
//        WechatUserCondition condition = new WechatUserCondition();
//        condition.setOpenId(myJson.getString("openid"));
//        WechatUserPo po = wechatUserService.queryWechatUser(condition);
//        log.info(">>>>>>>>>>>>>>>>>>>>wechatUserService.queryWechatUser>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
//        if(po == null){
//            po = new WechatUserPo();
//            po.setOpenId(myJson.getString("openid"));
//            po.setSex(myJson.getInteger("sex"));
//            po.setNickName(myJson.getString("nickname"));
//            po.setCountry(myJson.getString("country"));
//            po.setProvince(myJson.getString("province"));
//            po.setCity(myJson.getString("city"));
//            po.setHeadimgurl(myJson.getString("headimgurl"));
//            po.setDelFlag(2);   //未删除
//            po.setAddTime(new Date());
//            wechatUserService.adduser(po);
//        }
//
//        Map<String,String> RequestMap = new HashMap<String, String>();
//        RequestMap.put("openid",po.getOpenId());
//        RequestMap.put("sex",po.getSex().toString());
//        RequestMap.put("nickname",po.getNickName());
//        RequestMap.put("country",po.getCountry());
//        RequestMap.put("province",po.getProvince());
//        RequestMap.put("city",po.getCity());
//        RequestMap.put("headimgurl",po.getHeadimgurl());
//
//        String sss = HttpClient4Util.Post("http://daxuexiu.cn/oauth/userLogin",RequestMap,"UTF-8");
//
//        map.put("result","sucess");
//        map.put("code",200);
//        return map;
//    }

}
